﻿using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using UnitOfWork.Interfaces;
using Utility.Locators;
using Utility.Paging;

namespace UnitOfWork.EntityFramework
{
	public abstract class RepositoryBase<TEntity> where TEntity : class 
	{
		protected RepositoryBase(ILocator<ILinqProvider> linqProviderLocator)
		{
			LinqProviderLocator = linqProviderLocator;
		}

		protected IQueryable<TEntity> EntityQuery { get { return LinqProvider.Query<TEntity>(); } }
		protected ILinqProvider LinqProvider { get { return LinqProviderLocator.GetCurrent(); } }

		protected IEnumerable<T> Paged<T>(IQueryable<T> query, IQueryable<T> sortedQuery, PagingParameters paging)
		{
			Contract.Requires(query != null);
			Contract.Requires(sortedQuery != null);

			if (paging != null)
			{
				paging.TotalCount = query.Count();

				return sortedQuery
					.Skip(paging.PageIndex * paging.PageSize)
					.Take(paging.PageSize)
					.ToList();
			}
			else
				return sortedQuery.ToList();
		}

		private ILocator<ILinqProvider> LinqProviderLocator { get; set; }
	}
}